package cn.hqu.day01;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;

public class JavaLambdaWordCount {

    public static void main(String[] args) {
        SparkConf conf = new SparkConf().setAppName("JavaLambdaWordCount");
        // JavaSparkContext是对SparkContext的包装
        JavaSparkContext jsc = new JavaSparkContext(conf);

        // JavaSparkContext可以创建JavaRDD
        // JavaRDD包装了RDD
        JavaRDD<String> lines = jsc.textFile(args[0]);

        // 切分压平
//        JavaRDD<String> words = lines.flatMap(line -> Arrays.stream(line.split(" ")).iterator());
        JavaRDD<String> words = lines.flatMap(line -> {
            return Arrays.stream(line.split(" ")).iterator();
        });

        JavaPairRDD<String, Integer> wordAndOne = words.mapToPair(w -> new Tuple2<>(w, 1));


        // 聚合
        JavaPairRDD<String, Integer> reduced = wordAndOne.reduceByKey((a, b) -> a + b);

        // 交换
        JavaPairRDD<Integer, String> swaped = reduced.mapToPair(tp -> tp.swap());

        // 排序
        JavaPairRDD<Integer, String> sorted = swaped.sortByKey(false);

        JavaPairRDD<String, Integer> result = sorted.mapToPair(Tuple2::swap);

        // 保存到HDFS
        result.saveAsTextFile(args[1]);

        // 关闭sc
        jsc.stop();

    }
}
